﻿window.addEventListener('keydown', (e) => {
    if (e.key === "F12") {
        showDevTools()
    }
})
window.addEventListener('resize', resize);
function resize() {
    const height = document.documentElement.clientHeight - document.querySelector('.header').clientHeight - document.querySelector('.footer').clientHeight
    document.querySelector('.content').setAttribute('style', 'height:' + height + 'px')
}
window.addEventListener('load', (e) => {
    resize();
})
function msgbox(title = null, context = null, callback = null) {
    const cancelBtn = $('<button type="button" class="btn btn-sm" data-dismiss="modal">关闭</button>')
    const box = $('<div class="modal fade" id="dialog" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4 class="modal-title"></h4></div><div class="modal-body"><p></p></div><div class="modal-footer"></div></div></div></div>')
    if (typeof callback === 'function') {
        const okBtn = $('<button type="button" class="btn btn-sm" data-dismiss="modal">确定</button>')
        okBtn.on('click', callback);
        $('.modal-footer', box).append(okBtn);
    }
    $('.modal-footer', box).append(cancelBtn)
    if (title) {
        $('.modal-title', box).append(title)
    }
    if (context) {
        $('.modal-body > p', box).append(context)
    }
    box.on('hidden.bs.modal', (e) => {
        $(box).remove()
    })
    $(document.body).append(box)
    box.modal('show')
}
async function downloadChapter(chapter) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    const options = {
        method: 'GET',
        credentials: 'include',
        headers: headers
    };
    try {
        const response = await fetch(chapter.Url, options);
        const contentType = response.headers.get('Content-Type');
        if (contentType.match(/charset=gbk/i)) {
            await response.blob().then(blob => {
                return new Promise((resolve, reject) => {
                    var reader = new FileReader()
                    reader.onload = function (e) {
                        chapter.Content = reader.result;
                        resolve(chapter);
                    }
                    reader.onerror = function (err) {
                        console.error(err)
                        if (errorCallback) {
                            errorCallback(err)
                        }
                    }
                    reader.readAsText(blob, 'GBK')
                })
            })
        }
        else {
            chapter.Content = await response.text();
        }
        return chapter;
    }
    catch (err) {
        console.error(err)
        if (errorCallback) {
            errorCallback(err)
        }
    }
}
async function getFetch() {
    let url, data, errorCallback
    for (let i = 0; i < arguments.length; i++) {
        if (arguments.length <= 0) {
            console.error('Get function arguments errors')
            return
        }
        switch (typeof arguments[i]) {
            case 'string':
                url = arguments[i]
                break
            case 'object':
                data = arguments[i]
                break
            case 'function':
                errorCallback = arguments[i]
                break
        }
    }
    let headers = new Headers()
    if (!data) {
        headers.append('Content-Type', 'text/html;charset=utf-8')
    }
    else {
        headers.append('Content-Type', 'application/json')
    }
    let options = {
        method: 'GET',
        credentials: 'include',
        headers: headers
    }
    if (data) {
        options.body = JSON.stringify(data)
        options.method = 'POST'
    }
    try {
        const response = await fetch(url, options)
        let text
        const contentType = response.headers.get('Content-Type')
        if (contentType.match(/charset=gbk/i)) {
            text = await response.blob().then(blob => {
                return new Promise((resolve, reject) => {
                    var reader = new FileReader()
                    reader.onload = function (e) {
                        data ? resolve(JSON.parse(reader.result)) : resolve(reader.result)
                    }
                    reader.onerror = function (err) {
                        console.error(err)
                        if (errorCallback) {
                            errorCallback(err)
                        }
                    }
                    reader.readAsText(blob, 'GBK')
                })
            })
        }
        else {
            text = await response.text()
        }
        return data ? JSON.parse(text) : text
    }
    catch (err) {
        console.error(err)
        if (errorCallback) {
            errorCallback(err)
        }
    }
}
HTMLAnchorElement.prototype.toUrl = function (baseUrl) {
    return this.href.toUrl(baseUrl)
}
String.prototype.toUrl = function (baseUrl) {
    let startUrl = this.match('[^:]*://[^/]*/')
    let url = this.replace(/\\/g, '/')
    if (url.indexOf(startUrl) !== -1) {
        return baseUrl + url.replace(startUrl, '')
    }
    else if (url.substring(0, 2) === '//') {
        return url
    }
    else if (url.indexOf('//') !== -1) {
        return url
    }
    else {
        return baseUrl + url
    }
}
String.prototype.getInfoUrl = function (scheme, host) {
    const m = this.match('://([^/]*)/(.*)')
    if (m[1] && m[2]) {
        return scheme + '://' + m[1] + '/' + m[2]
    }
    let url = this
    if (url.indexOf('//') !== -1) {
        url = url.substring(url.indexOf('//') + 2)
    }
    if (url.indexOf('/') !== -1) {
        url = url.substring(url.indexOf('/'))
    }
    return scheme + '://' + host + url
}
Element.prototype.formatToString = function () {
    let context = this.outerHTML.replace(/<br[^>]*>/g, '\n')
    let element = document.createElement('div')
    element.innerHTML = context
    const lines = element.innerText.split('\n')
    context = ''
    for (let i = 0; i < lines.length; i++) {
        if (lines[i].trim() !== '') {
            context += lines[i].trim().replace(/&nbsp;/ig, '') + '\n'
        }
    }
    return context
}
NodeList.prototype.findTextContent = function (textContent) {
    const array = Array.from(this);
    let val = array.find((it) => it.textContent === textContent);
    for (let val of this) {
        if (val.textContent === textContent) {
            return val;
        }
    }
    return null;
}